<template>
  <div class="upload">
    <el-upload
      ref="uploadRef"
      :action="action"
      :headers="headers"
      :show-file-list="false"
      :before-upload="beforeUpload"
    >
      <slot> </slot>

      <template #tip>
        <div class="el-upload__tip">{{ tip }}</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useLogin from '@/stores/login.js'
import { upload } from '@/service/common'

const { t, locale } = useI18n()
const store = useLogin()

const router = useRouter()
const route = useRoute()

const emit = defineEmits(['change'])
const props = defineProps({
  tip: {
    type: String,
    default: ''
  }
})

// 接口地址
const action = ref(``)

// headers
const headers = ref({
  Platfrom: 1,
  Authorization: `Bearer ${store.token}`
})

// ref
const uploadRef = ref(null)

const beforeUpload = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }

  const fileData = new FormData()
  fileData.append('file', rawFile)

  upload(fileData).then(({ url }) => {
    emit('change', url)
  })

  return false
}
</script>

<style scoped lang="scss">
.upload {
}
</style>
